/// 用户状态管理
/// 
/// 管理用户列表和用户详情的状态
/// 使用Provider进行状态管理
/// 
/// 作者: Fluttert Team
/// 日期: 2024

import 'package:flutter/material.dart';
import '../models/user_model.dart';
import '../services/user_service.dart';
import '../widgets/common/error_widget.dart';

/// 用户状态管理类
/// 
/// 管理用户相关的状态和业务逻辑
class UserProvider extends ChangeNotifier {
  /// 用户服务实例
  final UserService _userService = UserService();

  /// 用户列表
  List<UserModel> _users = [];
  
  /// 当前选中的用户
  UserModel? _selectedUser;
  
  /// 是否正在加载
  bool _isLoading = false;
  
  /// 错误信息
  String? _error;

  /// 获取用户列表
  List<UserModel> get users => _users;
  
  /// 获取选中的用户
  UserModel? get selectedUser => _selectedUser;
  
  /// 获取加载状态
  bool get isLoading => _isLoading;
  
  /// 获取错误信息
  String? get error => _error;

  /// 获取用户列表
  /// 
  /// [refresh] 是否刷新列表
  Future<void> fetchUsers({bool refresh = false}) async {
    if (refresh) {
      _users.clear();
    }

    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final users = await _userService.getUserList();
      _users = users;
      _error = null;
    } catch (e) {
      _error = e.toString();
      _users = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 获取用户详情
  /// 
  /// [userId] 用户ID
  Future<void> fetchUserById(int userId) async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      _selectedUser = await _userService.getUserById(userId);
      _error = null;
    } catch (e) {
      _error = e.toString();
      _selectedUser = null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 创建用户
  /// 
  /// [name] 用户名
  /// [email] 邮箱
  /// [age] 年龄
  Future<bool> createUser({
    required String name,
    required String email,
    int? age,
  }) async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final newUser = await _userService.createUser(
        name: name,
        email: email,
        age: age,
      );
      _users.add(newUser);
      _error = null;
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = e.toString();
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  /// 更新用户信息
  /// 
  /// [userId] 用户ID
  /// [name] 新用户名
  /// [email] 新邮箱
  /// [age] 新年龄
  Future<bool> updateUser({
    required int userId,
    String? name,
    String? email,
    int? age,
  }) async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final updatedUser = await _userService.updateUser(
        userId: userId,
        name: name,
        email: email,
        age: age,
      );
      
      // 更新列表中的用户
      final index = _users.indexWhere((u) => u.id == updatedUser.id);
      if (index != -1) {
        _users[index] = updatedUser;
      }
      
      // 如果当前选中的用户被更新，也更新它
      if (_selectedUser?.id == updatedUser.id) {
        _selectedUser = updatedUser;
      }
      
      _error = null;
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = e.toString();
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  /// 删除用户
  /// 
  /// [userId] 用户ID
  Future<bool> deleteUser(int userId) async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      await _userService.deleteUser(userId);
      _users.removeWhere((u) => u.id == userId);
      
      // 如果删除的是当前选中的用户，清空选中状态
      if (_selectedUser?.id == userId) {
        _selectedUser = null;
      }
      
      _error = null;
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = e.toString();
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  /// 清空错误信息
  void clearError() {
    _error = null;
    notifyListeners();
  }
}

